package com.yunyao.framework.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yunyao.common.constant.enums.*;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.dto.excel.ProjectOrderExcelDto;
import com.yunyao.common.dto.order.ProjectOrderDto;
import com.yunyao.common.dto.project.OrderAuditAttachmentDto;
import com.yunyao.common.exception.BusinessException;
import com.yunyao.common.web.util.ConvertUtil;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.mapper.BamuPurchaseApplyMapper;
import com.yunyao.dao.model.BamuContractMaterial;
import com.yunyao.dao.model.BamuPoSupply;
import com.yunyao.dao.model.BamuPurchaseApply;
import com.yunyao.dao.model.BamuPurchaseApplyMaterial;
import com.yunyao.dao.model.BamuPurchaseConsignee;
import com.yunyao.dao.model.BamuPurchaseContract;
import com.yunyao.dao.model.BamuSaleContract;
import com.yunyao.dao.model.BamuSoSupply;
import com.yunyao.dao.model.BamuSoSupplyMaterial;
import com.yunyao.dao.model.BamuSupplyApply;
import com.yunyao.dao.model.BamuSupplyApplyMaterial;
import com.yunyao.dao.model.BamuSupplyConsignee;
import com.yunyao.dao.service.bamu.IBamuAuditConfirmHistoryService;
import com.yunyao.dao.service.bamu.IBamuContractMaterialService;
import com.yunyao.dao.service.bamu.IBamuPoSupplyService;
import com.yunyao.dao.service.bamu.IBamuPurchaseApplyMaterialService;
import com.yunyao.dao.service.bamu.IBamuPurchaseApplyService;
import com.yunyao.dao.service.bamu.IBamuPurchaseConsigneeService;
import com.yunyao.dao.service.bamu.IBamuPurchaseContractService;
import com.yunyao.dao.service.bamu.IBamuSaleContractService;
import com.yunyao.dao.service.bamu.IBamuSoSupplyMaterialService;
import com.yunyao.dao.service.bamu.IBamuSoSupplyService;
import com.yunyao.dao.service.bamu.IBamuSupplyApplyMaterialService;
import com.yunyao.dao.service.bamu.IBamuSupplyApplyService;
import com.yunyao.dao.service.bamu.IBamuSupplyConsigneeService;
import com.yunyao.framework.audit.ProjectOrderAuditHandle;
import com.yunyao.framework.dto.audit.ApprovalDto;
import com.yunyao.framework.dto.audit.SubmitApprovalDto;
import com.yunyao.framework.dto.projectorder.ProjectConsigneeSaveDto;
import com.yunyao.framework.dto.projectorder.ProjectMaterialSaveDto;
import com.yunyao.framework.dto.projectorder.ProjectOrderSaveDto;
import com.yunyao.framework.service.ProjectOrderService;
import com.yunyao.framework.vo.projectorder.CheckSupplyVO;
import com.yunyao.framework.vo.projectorder.OrderAuditAttachmentVO;
import com.yunyao.framework.vo.projectorder.OrderSnAndNameVO;
import com.yunyao.framework.vo.projectorder.ProjectOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author chenyejian
 * @date 2024-07-16
 */
@Slf4j
@Service
public class ProjectOrderServiceImpl implements ProjectOrderService {
    @Autowired
    private BamuPurchaseApplyMapper purchaseMappingMapper;
    private final String STATUS_AUDIT = "待云采确认";
    @Autowired
    private IBamuPurchaseApplyService ibamuPurchaseApplyService;
    @Autowired
    private IBamuSupplyApplyService iBamuSupplyApplyService;
    @Autowired
    private ProjectOrderAuditHandle projectOrderAuditHandle;
    @Autowired
    private IBamuSaleContractService iBamuSaleContractService;

    @Autowired
    private IBamuPurchaseContractService iBamuPurchaseContractService;

    @Autowired
    private IBamuPurchaseApplyMaterialService ibamuPurchaseApplyMaterialService;
    @Autowired
    private IBamuPurchaseConsigneeService ibamuPurchaseConsigneeService;
    @Autowired
    private IBamuSoSupplyService iBamuSoSupplyService;

    @Autowired
    private IBamuPoSupplyService iBamuPoSupplyService;
    @Autowired
    private IBamuSoSupplyMaterialService iBamuSoSupplyMaterialService;
    @Autowired
    private IBamuContractMaterialService iBamuContractMaterialService;

    @Autowired
    private IBamuSupplyApplyMaterialService iBamuSupplyApplyMaterialService;

    @Autowired
    private IBamuSupplyConsigneeService iBamuSupplyConsigneeService;

    @Autowired
    private IBamuAuditConfirmHistoryService auditConfirmHistoryService;

    @Override
    public YResult<PageResult<ProjectOrderVO>> pageList(ProjectOrderDto projectOrderDto) {
        // 分页查询
        IPage<BamuPurchaseApply> page =
                ibamuPurchaseApplyService.getPurchaseApplyList(projectOrderDto);
        // 处理查询结果
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<ProjectOrderVO> voList = daoToVoList(page.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(voList, page.getCurrent(), page.getSize(),
                page.getPages(), page.getTotal()));
    }

    @Override
    public YResult<ProjectOrderVO> getOrderDetailById(String id) {
        BamuPurchaseApply apply = ibamuPurchaseApplyService.getById(id);
        return YResult.success(dao2Vo(apply));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public YResult<String> saveOrUpdate(ProjectOrderSaveDto projectOrderSaveDto) {
        try {
            BamuSaleContract byIdNoDelete = iBamuSaleContractService.getByIdNoDelete(projectOrderSaveDto.getContractId());

            BamuPurchaseApply apply = saveDto2Dao(projectOrderSaveDto);
            boolean saveOrUpdate = ibamuPurchaseApplyService.saveOrUpdate(apply);
            if (!saveOrUpdate) {
                return YResult.error("保存失败");
            }
            List<ProjectMaterialSaveDto> projectMaterialSaveDtoList =
                    projectOrderSaveDto.getMaterialList();
            if (CollectionUtils.isNotEmpty(projectMaterialSaveDtoList)) {
                List<BamuPurchaseApplyMaterial> materialList = new ArrayList<>();
                for (ProjectMaterialSaveDto projectMaterialSaveDto : projectMaterialSaveDtoList) {
                    BamuPurchaseApplyMaterial bamuPurchaseApplyMaterial = new BamuPurchaseApplyMaterial();
                    BeanUtils.copyProperties(projectMaterialSaveDto, bamuPurchaseApplyMaterial);
                    bamuPurchaseApplyMaterial.setPurchaseApplyId(apply.getId());
                    bamuPurchaseApplyMaterial.setContractId(apply.getContractId());
                    String id = projectMaterialSaveDto.getId();
                    if (StringUtils.isNotBlank(id)) {
                        bamuPurchaseApplyMaterial.setId(id);
                    }
                    if (projectMaterialSaveDto.getApplyCountNum() == null) {
                        bamuPurchaseApplyMaterial.setApplyCountNum(BigDecimal.ZERO);
                    }
                    //本次下单数量
                    BigDecimal orderCount = projectMaterialSaveDto.getOrderCount();
                    //已订购数量
                    BigDecimal applyCountNum = bamuPurchaseApplyMaterial.getApplyCountNum();
                    //本次下单数量+已订购数量
                    BigDecimal num = applyCountNum.add(orderCount);

                    if (byIdNoDelete.getIsNumFlag() == 1) {
                        bamuPurchaseApplyMaterial.setContractCount(num);
                    } else {
                        int result = projectMaterialSaveDto.getMaterialNum().compareTo(num);
                        if (result < 0) {
                            return YResult.error("不允许超过合同材料数量！");
                        } else {
                            bamuPurchaseApplyMaterial.setContractCount(num);
                        }
                    }
                    materialList.add(bamuPurchaseApplyMaterial);
                }
                ibamuPurchaseApplyMaterialService.saveOrUpdateBatch(materialList);


            }
            BigDecimal taxTotalPrice =
                    ibamuPurchaseApplyMaterialService.getSumTaxTotalPriceByPurchaseApplyId(apply.getId());
            BigDecimal noTaxTotalPrice =
                    ibamuPurchaseApplyMaterialService.getSumNoTaxTotalPriceByPurchaseApplyId(apply.getId());
            /**
             * 含税总价
             */
            apply.setTaxTotalPrice(taxTotalPrice);
            /**
             * 不含税总价
             */
            apply.setNotaxTotalPrice(noTaxTotalPrice);
            ibamuPurchaseApplyService.saveOrUpdate(apply);
            /**
             * 根据 项目订单订购数量 更改合同中已供货数量
             */
            LambdaQueryWrapper<BamuPurchaseApplyMaterial> applyWrapper = new LambdaQueryWrapper<>();
            applyWrapper.eq(BamuPurchaseApplyMaterial::getContractId, apply.getContractId()).eq(BamuPurchaseApplyMaterial::getIsDeleted, DataDeletedStatus.NO.getType());
            List<BamuPurchaseApplyMaterial> purchaseApplyMaterialList =
                    ibamuPurchaseApplyMaterialService.list(applyWrapper);
            Map<String, BigDecimal> applyMap =
                    purchaseApplyMaterialList.stream().filter(x -> null != x.getOrderCount()).collect(Collectors.toMap(BamuPurchaseApplyMaterial::getMaterialCode, BamuPurchaseApplyMaterial::getOrderCount, BigDecimal::add));

            if (!applyMap.isEmpty()) {
                LambdaQueryWrapper<BamuContractMaterial> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BamuContractMaterial::getContractId, apply.getContractId()).eq(BamuContractMaterial::getIsDeleted, DataDeletedStatus.NO.getType());
                List<BamuContractMaterial> contractMaterials =
                        iBamuContractMaterialService.list(queryWrapper);
                if (contractMaterials != null && !contractMaterials.isEmpty()) {
                    List<BamuContractMaterial> updateList = new ArrayList<>();
                    for (BamuContractMaterial contractMaterial : contractMaterials) {
                        if (applyMap.containsKey(contractMaterial.getMaterialCode())) {
                            BigDecimal applyNum = applyMap.get(contractMaterial.getMaterialCode());
                            contractMaterial.setApplyNum(applyNum);
                            updateList.add(contractMaterial);
                        }
                    }
                    if (!updateList.isEmpty()) {
                        iBamuContractMaterialService.saveOrUpdateBatch(updateList);
                    }
                }
            }

            if (null != projectOrderSaveDto.getConsigneeList() && !projectOrderSaveDto.getConsigneeList().isEmpty()) {
                List<BamuPurchaseConsignee> consigneeList =
                        new ArrayList<>(projectOrderSaveDto.getConsigneeList().size());
                for (ProjectConsigneeSaveDto dto : projectOrderSaveDto.getConsigneeList()) {
                    BamuPurchaseConsignee consignee = convertConsigneeDto2Dao(dto);
                    consignee.setPurchaseApplyId(apply.getId());
                    consigneeList.add(consignee);
                }
                ibamuPurchaseConsigneeService.saveOrUpdateBatch(consigneeList);
            }

            /**
             * 同时生成供货订单
             */
            savePurchaseApply2BamuSupplyApply(apply);
            return YResult.success(apply.getId());
        } catch (Exception e) {
            log.error("ProjectOrderServiceImpl.saveOrUpdate error", e);
        }
        return YResult.error("保存失败");
    }

    /**
     * 创建供货订单
     *
     * @param
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean savePurchaseApply2BamuSupplyApply(BamuPurchaseApply apply) throws Exception {
        BamuSupplyApply supply = iBamuSupplyApplyService.getByPurchaseApplyId(apply.getId());
//        if (supply != null) {
//            log.error("供货订单已存在");
//            return false;
//        }
        try {
            BamuPurchaseContract purchaseContract =
                    iBamuPurchaseContractService.getById(apply.getPurchaseContractId());
            //TODO 暂且注释
            /*if (StringUtils.equals(purchaseContract.getContractMethod(), "1")) {
                return false;
            }*/
            // 获取差异价点
            BigDecimal diffPricePoints = purchaseContract.getDiffPricePoints();

            // 空值检查
            if (diffPricePoints == null) {
                // 如果差异价点为空，则直接0.00
                diffPricePoints = BigDecimal.ZERO;
            }
            // 计算价格调整比例
            BigDecimal percentage =
                    BigDecimal.ONE.subtract(diffPricePoints.divide(new BigDecimal("100"), 2,
                            RoundingMode.HALF_UP));

//            if (ConvertUtil.null2String(AuditStatusEnums.AUDIT_SUCCESS.getType()).equals(apply
//            .getAuditStatus())) {
            /**
             * 生成供货订单
             */
            if (supply == null) {
                supply = new BamuSupplyApply();
            }
            String id = supply.getId();

            BeanUtils.copyProperties(apply, supply);
            supply.setId(id);
            /**
             * 含税总价 * 价格调整比例
             */
            if (apply.getTaxTotalPrice() != null) {
                supply.setTaxTotalPrice(apply.getTaxTotalPrice().multiply(percentage));
            }
            /**
             * 不含税总价 * 价格调整比例
             */
            if (apply.getNotaxTotalPrice() != null) {
                supply.setNotaxTotalPrice(apply.getNotaxTotalPrice().multiply(percentage));
            }
            supply.setApplyId(apply.getId());
//            supply.setAuditStatus(AuditStatusEnums.AUDIT_SUCCESS.getType().toString());
//                supply.setOrderStatus("1");
            supply.setCopperDate(apply.getCopperDate());
//            supply.setSupplyStatus(SupplyStatus.SUPPLY_ING.getType());
            supply.setFlowSubmitDate(apply.getFlowSubmitDate());
            supply.setContractId(purchaseContract.getId());
            supply.setContractName(purchaseContract.getContractName());
            supply.setContractMethod(purchaseContract.getContractMethod());
            iBamuSupplyApplyService.saveOrUpdate(supply);

            LambdaQueryWrapper<BamuPurchaseApplyMaterial> materialLambdaQueryWrapper =
                    new LambdaQueryWrapper<>();
            materialLambdaQueryWrapper.eq(BamuPurchaseApplyMaterial::getPurchaseApplyId,
                    apply.getId()).eq(BamuPurchaseApplyMaterial::getIsDeleted,
                    DataDeletedStatus.NO.getType());
            List<BamuPurchaseApplyMaterial> purchaseApplyMaterialList =
                    ibamuPurchaseApplyMaterialService.list(materialLambdaQueryWrapper);

            /**
             * 保存供货订单材料
             */
            List<BamuSupplyApplyMaterial> saveMaterialList =
                    new ArrayList<>(purchaseApplyMaterialList.size());
            if (CollectionUtils.isNotEmpty(purchaseApplyMaterialList)) {
                /**
                 * 删除原有供货订单材料
                 */
                if (supply != null && StringUtils.isNotEmpty(supply.getId())) {
                    // 使用更明确的条件判断来避免潜在的空指针异常
                    List<BamuSupplyApplyMaterial> oldSupplyMaterialList =
                            iBamuSupplyApplyMaterialService.list(new LambdaQueryWrapper<BamuSupplyApplyMaterial>().eq(BamuSupplyApplyMaterial::getPurchaseApplyId, supply.getId()));

                    if (CollectionUtils.isNotEmpty(oldSupplyMaterialList)) {
                        try {
                            // 尝试删除旧材料列表
                            iBamuSupplyApplyMaterialService.removeBatchByIds(oldSupplyMaterialList);
                        } catch (Exception e) {
                            // 异常处理逻辑
                            log.error("删除供货订单材料失败", e);
                            throw e; // 可以根据实际情况决定是否需要重新抛出异常
                        }
                    }
                } else {
                    // 如果 supply 或者 supply.getId() 为空，则不执行删除操作
                    log.warn("供货订单信息或ID为空，无法删除原有供货订单材料");
                }
                for (BamuPurchaseApplyMaterial purchaseApplyMaterial : purchaseApplyMaterialList) {
                    BamuSupplyApplyMaterial supplyApplyMaterial = new BamuSupplyApplyMaterial();
                    BeanUtils.copyProperties(purchaseApplyMaterial, supplyApplyMaterial);
                    supplyApplyMaterial.setId(null);
                    supplyApplyMaterial.setPurchaseApplyId(supply.getId());
                    supplyApplyMaterial.setOrderMaterialId(purchaseApplyMaterial.getId());
                    supplyApplyMaterial.setContractId(purchaseContract.getId());
                    /**
                     * 含税单价 * 价格调整比例
                     */
                    if (purchaseApplyMaterial.getIncludingTaxUnitPrice() != null) {
                        supplyApplyMaterial.setIncludingTaxUnitPrice(purchaseApplyMaterial.getIncludingTaxUnitPrice().multiply(percentage));
                    }
                    /**
                     * 不含税单价 * 价格调整比例
                     */
                    if (purchaseApplyMaterial.getExcludingTaxUnitPrice() != null) {
                        supplyApplyMaterial.setExcludingTaxUnitPrice(purchaseApplyMaterial.getExcludingTaxUnitPrice().multiply(percentage));
                    }
                    /**
                     * 材料含税总价 * 价格调整比例
                     */
                    if (purchaseApplyMaterial.getIncludingTaxTotalPrice() != null) {
                        supplyApplyMaterial.setIncludingTaxTotalPrice(purchaseApplyMaterial.getIncludingTaxTotalPrice().multiply(percentage));
                    }

                    saveMaterialList.add(supplyApplyMaterial);
                }
                iBamuSupplyApplyMaterialService.saveBatch(saveMaterialList);
            }

            /**
             * 保存供货订单收货人
             */
            LambdaQueryWrapper<BamuPurchaseConsignee> consigneeLambdaQueryWrapper =
                    new LambdaQueryWrapper<>();
            consigneeLambdaQueryWrapper.eq(BamuPurchaseConsignee::getPurchaseApplyId,
                    apply.getId()).eq(BamuPurchaseConsignee::getIsDeleted,
                    DataDeletedStatus.NO.getType());
            List<BamuPurchaseConsignee> purchaseConsigneeList =
                    ibamuPurchaseConsigneeService.list(consigneeLambdaQueryWrapper);
            List<BamuSupplyConsignee> saveConsigneeList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(purchaseConsigneeList)) {
                for (BamuPurchaseConsignee purchaseConsignee : purchaseConsigneeList) {
                    BamuSupplyConsignee supplyConsignee = new BamuSupplyConsignee();
                    BeanUtils.copyProperties(purchaseConsignee, supplyConsignee);
//                        supplyConsignee.setId(null);
                    supplyConsignee.setPurchaseApplyId(supply.getId());
                    saveConsigneeList.add(supplyConsignee);
                }
                iBamuSupplyConsigneeService.saveBatch(saveConsigneeList);
            }
            return true;

//            }
        } catch (Exception e) {
            log.error("项目订单审核成功 创建供货订单失败", e);
            return false;
        }
    }


    @Override
    public YResult<String> deleteByIds(String[] ids) {
        List<BamuPurchaseApply> applyList = new ArrayList<>(ids.length);
        applyList = ibamuPurchaseApplyService.listByIds(Arrays.asList(ids));
        for (BamuPurchaseApply apply : applyList) {
            apply.setIsDeleted(DataDeletedStatus.YES.getType());
        }
        ibamuPurchaseApplyService.saveOrUpdateBatch(applyList);
        return YResult.success("删除成功");
    }

    /**
     * 项目订单供货完成
     *
     * @param id
     * @return
     */
    @Override
    public YResult<String> supplyFinish(String id) {
        /**
         * 项目订单
         */
        BamuPurchaseApply apply = ibamuPurchaseApplyService.getById(id);
        if (apply == null) {
            return YResult.error("未找到对应的供货申请");
        }
        if (null == apply.getSupplyStatus() || apply.getSupplyStatus() <= SupplyStatus.SUPPLY_ING.getType()) {
            return YResult.error("待供货或供货未开始，不允许供货完成！");
        }


        LambdaQueryWrapper<BamuSoSupply> supplyLambdaQueryWrapper = new LambdaQueryWrapper<>();
        supplyLambdaQueryWrapper.eq(BamuSoSupply::getApplyId, apply.getId());
        List<BamuSoSupply> supplyList = iBamuSoSupplyService.list(supplyLambdaQueryWrapper);

        /**
         * 循环验收清单
         */
        for (BamuSoSupply supply : supplyList) {
            supply.setSupplyStatus(SupplyListStatus.WAIT_PROJECT_ACCEPTANCE.getType());
            supply.setSupplyTime(new Date());

            /**
             * 查询供货清单修改状态
             */
            LambdaQueryWrapper<BamuPoSupply> poSupplyLambdaQueryWrapper =
                    new LambdaQueryWrapper<>();
            poSupplyLambdaQueryWrapper.eq(BamuPoSupply::getId, supply.getPoSupplyId());
            List<BamuPoSupply> poSupplyList = iBamuPoSupplyService.list(poSupplyLambdaQueryWrapper);
            for (BamuPoSupply poSupply : poSupplyList) {
                poSupply.setSupplyStatus(SupplyListStatus.WAIT_PROJECT_ACCEPTANCE.getType());
                poSupply.setSupplyTime(new Date());
            }
            iBamuPoSupplyService.saveOrUpdateBatch(poSupplyList);
        }
        iBamuSoSupplyService.saveOrUpdateBatch(supplyList);


        apply.setSupplyConfirmDate(new Date());
        apply.setSupplyStatus(SupplyStatus.SUPPLY_COMPLETED.getType());

        /**
         * 供货订单
         */
        BamuSupplyApply supplyApply = iBamuSupplyApplyService.getByPurchaseApplyId(apply.getId());
        if (supplyApply != null) {
            supplyApply.setSupplyStatus(SupplyStatus.SUPPLY_COMPLETED.getType());
            supplyApply.setSupplyConfirmDate(new Date());
            iBamuSupplyApplyService.saveOrUpdate(supplyApply);
        }
        return ibamuPurchaseApplyService.saveOrUpdate(apply) ? YResult.success("供货完成") :
                YResult.error("供货完成失败");
    }


    private List<ProjectOrderVO> daoToVoList(List<BamuPurchaseApply> daoList) {
        List<ProjectOrderVO> voList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(daoList)) {
            return daoList.stream().map(this::dao2Vo).collect(Collectors.toList());
        }
        return voList;
    }

    /**
     * 转化并格式化
     *
     * @param apply
     * @return ProjectOrderVO
     */
    private ProjectOrderVO dao2Vo(BamuPurchaseApply apply) {
        ProjectOrderVO vo = new ProjectOrderVO();
        try {
            BeanUtils.copyProperties(apply, vo);
            StringBuilder status = new StringBuilder();


            String orderStatus = "";
            if ((apply.getSupplyStatus() == null || apply.getSupplyStatus() == 0) && ConvertUtil.getIntValue(apply.getAuditStatus(), -1) != AuditStatusEnums.AUDIT_SUCCESS.getType()) {
                orderStatus =
                        AuditStatusEnums.getDescriptionByType(ConvertUtil.getIntValue(apply.getAuditStatus()));
            } else {
                if (apply.getSupplyStatus() == SupplyStatus.SUPPLY_COMPLETION_ACCEPTANCE.getType()) {
                    if (ConvertUtil.getIntValue(apply.getAuditStatus()) == AuditStatusEnums.AUDIT_REJECT.getType() || ConvertUtil.getIntValue(apply.getAuditStatus()) == AuditStatusEnums.AUDIT_REVOCATION.getType())
                        status.append(apply.getAuditStatus()).append("8");
                    orderStatus = OrderStatus.getDescriptionByType(status.toString());
                } else {
                    orderStatus = SupplyStatus.getDescriptionByType(apply.getSupplyStatus());
                }
            }
            /**
             * 审批中改为，待云采确认
             */
            if (orderStatus.equals(OrderStatus.APPROVAL_IN_PROGRESS.getDescription())) {
                orderStatus = STATUS_AUDIT;
            }
            vo.setOrderStatus(orderStatus);
            vo.setProjectInvoiceStatus(InvoiceStatusStatus.getDescriptionByType(apply.getProjectInvoiceStatus()));
            vo.setSupplyInvoiceStatus(InvoiceStatusStatus.getDescriptionByType(apply.getSupplyInvoiceStatus()));
            vo.setSettlementStatus(SettlementStatus.getDescriptionByType(apply.getSettlementStatus()));
            vo.setProjectReconciliationStatus(ReconciliationStatus.getDescriptionByType(apply.getProjectReconciliationStatus()));
            vo.setSupplierReconciliationStatus(ReconciliationStatus.getDescriptionByType(apply.getSupplierReconciliationStatus()));
//            vo.setCreatedAt(ConvertUtil.getFormatDate(apply.getCreatedAt(), false, "yyyy-MM-dd"));
            vo.setCopperDate(ConvertUtil.getFormatDate(apply.getCopperDate(), false, "yyyy-MM-dd"));
            vo.setReceivingTime(ConvertUtil.getFormatDate(apply.getReceivingTime(), false, "yyyy"
                    + "-MM-dd"));
            vo.setSupplyConfirmDate(ConvertUtil.getFormatDate(apply.getSupplyConfirmDate(), false
                    , "yyyy-MM-dd"));
            vo.setTakeAt(ConvertUtil.getFormatDate(apply.getTakeAt(), false, "yyyy-MM-dd"));
            vo.setFlowSubmitDate(ConvertUtil.getFormatDate(apply.getFlowSubmitDate(), false,
                    "yyyy-MM-dd"));

            String auditStatus = apply.getAuditStatus();
            String processInstanceId = apply.getProcessInstanceId();
            String modelSchemeInfoId = apply.getModelSchemeInfoId();
            if (StringUtils.isNotBlank(auditStatus) && StringUtils.equals(auditStatus,
                    AuditStatusEnums.AUDIT.getType().toString()) && StringUtils.isNotBlank(modelSchemeInfoId) && StringUtils.isNotBlank(processInstanceId)) {
                vo.setAuditButton(projectOrderAuditHandle.userIsAuditButton(modelSchemeInfoId,
                        processInstanceId));
            }

        } catch (Exception e) {
            log.error("ProjectOrderServiceImpl.daoToVo error", e);
        }
        return vo;
    }


    /**
     * projectOrderSaveDto 转 BamuPurchaseApply
     */
    private BamuPurchaseApply saveDto2Dao(ProjectOrderSaveDto projectOrderSaveDto) {
        BamuPurchaseApply apply = new BamuPurchaseApply();
        apply.setId(projectOrderSaveDto.getId());
        try {
            if (StringUtils.isNotEmpty(projectOrderSaveDto.getAttachFiles()) && ConvertUtil.isValidNotEmptyJson(projectOrderSaveDto.getAttachFiles())) {
                apply.setAttachFiles(projectOrderSaveDto.getAttachFiles());
            } else {
                apply.setAttachFiles("[]");
            }
            /**
             * 销售合同
             */
            BamuSaleContract saleContract =
                    iBamuSaleContractService.getById(projectOrderSaveDto.getContractId());
            BamuPurchaseContract purchaseContract =
                    iBamuPurchaseContractService.getBySaleContractId(saleContract.getId());
            apply.setOrderSn(saleContract.getContractNo());
            apply.setOrderName(saleContract.getContractName());
            apply.setOrderDesc(saleContract.getMark());
            apply.setContractMethod(saleContract.getContractMethod());
            apply.setContractNo(saleContract.getContractNo());
            apply.setContractName(saleContract.getContractName());
            apply.setPurchaseContractName(saleContract.getMainContractName());
            apply.setSupplierId(saleContract.getSupplierDeptId());
            apply.setSupplierName(saleContract.getSupplierDeptName());
            apply.setProjectId(saleContract.getProjectId());
            apply.setProjectName(saleContract.getProjectName());
            apply.setContractId(saleContract.getId());

            apply.setPurchaseContractId(purchaseContract.getId());
            apply.setReceivingTime(ConvertUtil.getString2Date(projectOrderSaveDto.getReceivingTime(), "yyyy-MM-dd"));
            apply.setCopperDate(ConvertUtil.getString2Date(projectOrderSaveDto.getCopperDate(),
                    "yyyy-MM-dd"));
            apply.setCopperPrice(projectOrderSaveDto.getCopperPrice());
            apply.setBasePrice(projectOrderSaveDto.getBasePrice());
            apply.setIncreasePrice(projectOrderSaveDto.getIncreasePrice());
            apply.setIncreaseRate(projectOrderSaveDto.getIncreaseRate());
            apply.setCopperUpdatePersonId(BaseContext.getUserId());
            apply.setCopperUpdatePersonName(BaseContext.getUserInfo().getRealName());
            apply.setPriceType(projectOrderSaveDto.getPriceType());
            apply.setPriceTypeMark(projectOrderSaveDto.getPriceTypeMark());
            /**
             * 项目订单存销售合同实际总价
             */
            apply.setPurchaseContractTaxTotalPrice(saleContract.getContractTotalRealPrice());
            apply.setPurchaseContractName(purchaseContract.getContractName());
            apply.setProjectDeptId(purchaseContract.getProjectDeptId());
            apply.setProjectDeptName(purchaseContract.getProjectDeptName());
            apply.setPurchaseDeptId(purchaseContract.getPurchaseDeptId());
            apply.setPurchaseDeptName(purchaseContract.getPurchaseDeptName());

            apply.setSaleDeptId(saleContract.getProjectDeptId());
            apply.setSaleDeptName(saleContract.getProjectDeptName());

            //新增的时候
            if (projectOrderSaveDto.getId() == null || StringUtils.isEmpty(projectOrderSaveDto.getId())) {
                apply.setAuditStatus(ConvertUtil.null2String(AuditStatusEnums.SUBMITTED.getType()));
                apply.setId(null);
            }
        } catch (Exception e) {
            log.error("ProjectOrderServiceImpl.voToDao error", e);
        }
        return apply;
    }


    /**
     * 提交审批操作
     * 该方法接收一个审批数据传输对象（SaleContractSubmitApprovalDto），尝试提交销售合同的审批流程
     * 如果提交成功，返回一个成功结果，包含审批的ID；如果提交过程中发生异常，
     * 则返回一个错误结果，包含异常信息
     *
     * @param approvalDto 审批数据传输对象，包含审批所需的必要信息
     * @return YResult<String> 返回一个包含结果状态和审批ID的结果对象
     */
    @Override
    public YResult<String> submitApproval(SubmitApprovalDto approvalDto) {
        try {
            // 调用处理类的submit方法，传入审批ID，执行审批提交操作
            projectOrderAuditHandle.submit(approvalDto.getId());
            // 如果审批提交成功，返回成功结果，包含审批的ID
            return YResult.success(approvalDto.getId());
        } catch (Exception e) {
            // 如果审批提交过程中发生异常，返回错误结果，包含异常信息
            return YResult.error(e.getMessage());
        }
    }


    /**
     * 审批销售合同
     * 该方法接收一个销售合同审批数据传输对象，并尝试对其进行审批操作
     * 如果审批成功，返回一个表示成功的YResult对象，包含审批后的ID
     * 如果审批过程中出现异常，返回一个表示错误的YResult对象，包含错误信息
     *
     * @param approvalDto 销售合同审批Dto，包含审批所需信息
     * @return YResult对象，表示审批结果
     */
    @Override
    public YResult<String> approval(ApprovalDto approvalDto) {
        try {
            // 调用审批处理类的approval方法进行审批操作
            projectOrderAuditHandle.approval(approvalDto);
            // 审批成功后，返回成功结果，携带审批后的ID
            return YResult.success(approvalDto.getId());
        } catch (Exception e) {
            // 审批过程中发生异常，返回错误结果，携带异常信息
            return YResult.error(e.getMessage());
        }
    }

    @Override
    public YResult<String> revocation(ApprovalDto approvalDto) {
        try {
            LambdaQueryWrapper<BamuSupplyApply> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BamuSupplyApply::getApplyId, approvalDto.getId()).eq(BamuSupplyApply::getIsDeleted, DataDeletedStatus.NO.getType());
            List<BamuSupplyApply> supplyApplyList = iBamuSupplyApplyService.list(queryWrapper);
//            if (null != supplyApply) {
//                return YResult.error("请删除该供货订单后操作");
//            }
            LambdaQueryWrapper<BamuPurchaseApply> query = new LambdaQueryWrapper<>();
            query.eq(BamuPurchaseApply::getId, approvalDto.getId()).eq(BamuPurchaseApply::getIsDeleted, DataDeletedStatus.NO.getType());
            BamuPurchaseApply iBamuPurchaseApply = ibamuPurchaseApplyService.getOne(query);
            if (null != iBamuPurchaseApply) {
                if (ConvertUtil.null2String(AuditStatusEnums.SUBMITTED.getType()).equals(iBamuPurchaseApply.getAuditStatus())) {
                    return YResult.error("审核待提交，无需撤回");
                }
                if (ConvertUtil.null2String(AuditStatusEnums.AUDIT_REJECT.getType()).equals(iBamuPurchaseApply.getAuditStatus())) {
                    return YResult.error("审核已驳回，无需撤回");
                }
                if (ConvertUtil.null2String(AuditStatusEnums.AUDIT_SUCCESS.getType()).equals(iBamuPurchaseApply.getAuditStatus())) {
                    return YResult.error("审核已通过，不允许撤回");
                }
                iBamuPurchaseApply.setAuditStatus(ConvertUtil.null2String(AuditStatusEnums.AUDIT_REVOCATION.getType()));
                ibamuPurchaseApplyService.updateById(iBamuPurchaseApply);
//                projectOrderAuditHandle.revocation(approvalDto);
            }
            // 审批成功后，返回成功结果，携带审批后的ID
            return YResult.success(approvalDto.getId());
        } catch (Exception e) {
            // 审批过程中发生异常，返回错误结果，携带异常信息
            return YResult.error(e.getMessage());
        }
    }

    /**
     * @param orderDto
     * @return
     */
    @Override
    public YResult<String> audit(ProjectOrderDto orderDto) {
        BamuPurchaseApply apply = ibamuPurchaseApplyService.getById(orderDto.getId());
        /**
         * 供货确认
         */
//        apply.setShipmentAt(new Date());
//        apply.setShipmentDesc(orderDto.getAuditReason());
//        apply.setShipmentFiles(orderDto.getAuditFileUrl());
//        apply.setShipmentUserId(BaseContext.getUserId());
//        apply.setShipmentUserName(BaseContext.getUserInfo().getRealName());
        apply.setProjectConfirmFile(orderDto.getAuditFileUrl());
//        apply.setstat(SupplyStatus.SUPPLY_ING.getType());

        auditConfirmHistoryService.insertRecord(apply.getId(), new Date(), null,
                orderDto.getAuditFileUrl(), orderDto.getAuditReason(),
                ConvertUtil.getIntValue(orderDto.getAuditStatus()), "0",
                BaseContext.getUserInfo().getRealName());
        ibamuPurchaseApplyService.saveOrUpdate(apply);
        return YResult.success("审核成功");
    }


    /**
     * saveDto转化为dao
     */
    private BamuPurchaseApplyMaterial convertMaterialDto2Dao(ProjectMaterialSaveDto saveDto) {
        BamuPurchaseApplyMaterial bamuPurchaseApplyMaterial = new BamuPurchaseApplyMaterial();
        if (saveDto.getContractCount() == null) {
            saveDto.setContractCount(saveDto.getMaterialNum());
        }
        BeanUtils.copyProperties(saveDto, bamuPurchaseApplyMaterial);
        bamuPurchaseApplyMaterial.setIncludingTaxTotalPrice(saveDto.getIncludingTaxTotalPrice());
        bamuPurchaseApplyMaterial.setContractMaterialId(saveDto.getContractMaterialId());
        return bamuPurchaseApplyMaterial;
    }


    /**
     * saveDto转化为dao
     */
    private BamuPurchaseConsignee convertConsigneeDto2Dao(ProjectConsigneeSaveDto saveDto) {
        BamuPurchaseConsignee bamuPurchaseConsignee = new BamuPurchaseConsignee();
        BeanUtils.copyProperties(saveDto, bamuPurchaseConsignee);
        return bamuPurchaseConsignee;
    }


    public YResult<OrderSnAndNameVO> getSnAndNameByContractId(String contractId) {
        BamuSaleContract saleContract = iBamuSaleContractService.getById(contractId);
        if (saleContract == null) {
            return YResult.error("合同不存在");
        }
        OrderSnAndNameVO orderSnAndNameVO = new OrderSnAndNameVO();
        LambdaQueryWrapper<BamuPurchaseApply> query = new LambdaQueryWrapper<>();
        query.eq(BamuPurchaseApply::getContractId, contractId).eq(BamuPurchaseApply::getIsDeleted
                , DataDeletedStatus.NO.getType()).orderByDesc(BamuPurchaseApply::getOrderSn);
        List<BamuPurchaseApply> applyList = ibamuPurchaseApplyService.list(query);
        /**
         * 合同方式0电线电缆及光纤光缆 1 电梯及扶梯   2024-06-12电线电缆及光纤光缆采购第[2]批
         */
        Integer applyNum = 0;
        StringBuffer orderName = new StringBuffer();
        if (CollectionUtils.isEmpty(applyList)) {
            orderSnAndNameVO.setOrderSn(saleContract.getContractNo() + "-001");
        } else {
            applyNum = applyList.size();
            orderSnAndNameVO.setOrderSn(saleContract.getContractNo() + "-" + String.format("%03d"
                    , applyNum + 1));
        }

        orderName.append(ConvertUtil.getFormatDate(new Date(), true, "yyyy-MM-dd")).append("1".equals(saleContract.getContractMethod()) ? "电梯及扶梯" : "电线电缆及光纤光缆").append("采购第[").append(applyNum + 1).append("]批");
        orderSnAndNameVO.setOrderName(orderName.toString());
        orderSnAndNameVO.setContractName(saleContract.getContractName());
        orderSnAndNameVO.setContractId(saleContract.getId());
        orderSnAndNameVO.setContractNo(saleContract.getContractNo());
        return YResult.success(orderSnAndNameVO);
    }

    @Override
    public YResult<OrderAuditAttachmentVO> getAttachmentInfo(String orderId) {
        OrderAuditAttachmentVO orderAuditAttachmentVO = new OrderAuditAttachmentVO();
        /**
         * 采购订单
         */
        BamuPurchaseApply bamuPurchaseApply = ibamuPurchaseApplyService.getById(orderId);
        if (bamuPurchaseApply == null) {
            return YResult.error("采购订单不存在");
        }
//        List<AttachFileDto> attachFileDtoList = JSONArray.parseArray(bamuPurchaseApply
//        .getAttachFiles(), AttachFileDto.class);
//        List<FileDto> fileDtoList = JSONArray.parseArray(bamuPurchaseApply.getAttachFiles(),
//        FileDto.class);
//        if (CollectionUtils.isNotEmpty(attachFileDtoList) && attachFileDtoList.size()>0 &&
//        StringUtils.isNotEmpty(attachFileDtoList.get(0).getUrl())) {
//            orderAuditAttachmentVO.setProjectOrderFile(attachFileDtoList.stream().map
//            (attachFileDto -> ConvertUtil.attachDto2FileDto(attachFileDto)).collect(Collectors
//            .toList()));
//        }else if (CollectionUtils.isNotEmpty(fileDtoList)){
//            orderAuditAttachmentVO.setProjectOrderFile(fileDtoList);
//        }
//
        orderAuditAttachmentVO.setProjectOrderFile(ConvertUtil.getFileDtoList(bamuPurchaseApply.getAttachFiles()));

        orderAuditAttachmentVO.setProjectOrderCloudFile(ConvertUtil.getFileDtoList(bamuPurchaseApply.getProjectConfirmFile()));
        orderAuditAttachmentVO.setSupplyOrderCloudFile(ConvertUtil.getFileDtoList(bamuPurchaseApply.getSupplyConfirmFile()));
        orderAuditAttachmentVO.setSupplyOrderSn(bamuPurchaseApply.getOrderSn());
        orderAuditAttachmentVO.setSupplyOrderName(bamuPurchaseApply.getOrderName());
        orderAuditAttachmentVO.setBizId(bamuPurchaseApply.getId());

        BamuSupplyApply bamuSupplyApply = iBamuSupplyApplyService.getByPurchaseApplyId(orderId);
        if (bamuSupplyApply != null) {
            orderAuditAttachmentVO.setSupplyOrderId(bamuSupplyApply.getId());
        }
        return YResult.success(orderAuditAttachmentVO);
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public YResult<String> saveAuditCloudAttachment(OrderAuditAttachmentDto attachmentDto) {
        BamuPurchaseApply bamuPurchaseApply =
                ibamuPurchaseApplyService.getById(attachmentDto.getBizId());
        BamuSupplyApply bamuSupplyApply =
                iBamuSupplyApplyService.getByPurchaseApplyId(attachmentDto.getBizId());
        bamuPurchaseApply.setSupplyConfirmFile(!CollectionUtils.isNotEmpty(attachmentDto.getSupplyOrderCloudFile()) ? "[]" : JSONArray.toJSONString(attachmentDto.getSupplyOrderCloudFile()));
        bamuPurchaseApply.setProjectConfirmFile(!CollectionUtils.isNotEmpty(attachmentDto.getProjectOrderCloudFile()) ? "[]" : JSONArray.toJSONString(attachmentDto.getProjectOrderCloudFile()));
        if (bamuSupplyApply != null) {
            bamuSupplyApply.setSupplyConfirmFile(!CollectionUtils.isNotEmpty(attachmentDto.getSupplyOrderCloudFile()) ? "[]" : JSONArray.toJSONString(attachmentDto.getSupplyOrderCloudFile()));
            bamuSupplyApply.setProjectConfirmFile(!CollectionUtils.isNotEmpty(attachmentDto.getProjectOrderCloudFile()) ? "[]" : JSONArray.toJSONString(attachmentDto.getProjectOrderCloudFile()));
        }
        //下面原代码
        /*if (CollectionUtils.isNotEmpty(attachmentDto.getSupplyOrderCloudFile())) {
            bamuPurchaseApply.setSupplyConfirmFile(JSONArray.toJSONString(attachmentDto.getSupplyOrderCloudFile()));
            bamuSupplyApply.setSupplyConfirmFile(JSONArray.toJSONString(attachmentDto.getSupplyOrderCloudFile()));
        } else {
            bamuPurchaseApply.setSupplyConfirmFile("[]");
            bamuSupplyApply.setSupplyConfirmFile("[]");
        }
        if (CollectionUtils.isNotEmpty(attachmentDto.getProjectOrderCloudFile())) {
            bamuPurchaseApply.setProjectConfirmFile(JSONArray.toJSONString(attachmentDto.getProjectOrderCloudFile()));
            bamuSupplyApply.setProjectConfirmFile(JSONArray.toJSONString(attachmentDto.getProjectOrderCloudFile()));
        } else {
            bamuPurchaseApply.setProjectConfirmFile("[]");
            bamuSupplyApply.setProjectConfirmFile("[]");
        }*/
        ibamuPurchaseApplyService.updateById(bamuPurchaseApply);
        iBamuSupplyApplyService.updateById(bamuSupplyApply);
        return YResult.success(bamuPurchaseApply.getId());
    }

    @Override
    public YResult<String> checkTotalPriceAndMaterialSum(ProjectOrderSaveDto projectOrderSaveDto) {
        BamuSaleContract bamuSaleContract =
                iBamuSaleContractService.getById(projectOrderSaveDto.getContractId());
        /**
         * 允许超合同金额，允许超合同数量，不做任何限制，直接返回
         */
        if (bamuSaleContract != null && 1 == ConvertUtil.getIntValue(bamuSaleContract.getIsPriceFlag(), 0) && 1 == ConvertUtil.getIntValue(bamuSaleContract.getIsNumFlag(), 0)) {
            return YResult.success("不限制");
        }

        StringBuffer errorMsg = new StringBuffer();

        /**
         * 不允许超过合同数量判断
         */
        StringBuffer errorNumMsg = new StringBuffer();
        BigDecimal totalPrice = new BigDecimal(0);
        if (0 == ConvertUtil.getIntValue(bamuSaleContract.getIsNumFlag(), 0)) {

            List<ProjectMaterialSaveDto> materialSaveDtoList =
                    projectOrderSaveDto.getMaterialList();

            /**
             * materialSaveDtoList合并相同的materialCode中的OrderCount数量
             */
            if (CollectionUtils.isNotEmpty(materialSaveDtoList)) {
                Map<String, ProjectMaterialSaveDto> materialMap = new HashMap<>();
                for (ProjectMaterialSaveDto materialSaveDto : materialSaveDtoList) {
                    if (materialSaveDto.getOrderCount() == null) {
                        materialSaveDto.setOrderCount(BigDecimal.ZERO);
                    }
                    if (!materialMap.containsKey(materialSaveDto.getMaterialCode())) {
                        materialMap.put(materialSaveDto.getMaterialCode(), materialSaveDto);
                        continue;
                    } else {
                        materialMap.get(materialSaveDto.getMaterialCode()).setOrderCount(materialMap.get(materialSaveDto.getMaterialCode()).getOrderCount().add(materialSaveDto.getOrderCount()));
                    }
                    totalPrice =
                            totalPrice.add(ConvertUtil.getBigDecimalValue(materialSaveDto.getIncludingTaxTotalPrice(), BigDecimal.ZERO));
                }
                if (null != materialMap && materialMap.size() > 0) {
                    for (Map.Entry<String, ProjectMaterialSaveDto> entry : materialMap.entrySet()) {
                        ProjectMaterialSaveDto dto = entry.getValue();
                        if (ConvertUtil.getBigDecimalValue(dto.getApplyCountNum(),
                                BigDecimal.ZERO).add(ConvertUtil.getBigDecimalValue(dto.getOrderCount(), BigDecimal.ZERO)).compareTo(ConvertUtil.getBigDecimalValue(dto.getMaterialNum(), BigDecimal.ZERO)) > 0) {
                            if (errorNumMsg.length() == 0) {
                                errorNumMsg.append("材料编码").append(dto.getMaterialCode()).append(
                                        "，");
                            } else {
                                errorNumMsg.append(dto.getMaterialCode()).append("，");
                            }
                        }
                    }
                    if (errorNumMsg.length() > 0) {
                        errorNumMsg.append("超出合同数量，请修改后重试；");
                        return YResult.error(errorNumMsg.toString());
                    }
                }
            }
        }


        /**
         * 不允许超过合同金额判断
         */
        if (0 == ConvertUtil.getIntValue(bamuSaleContract.getIsPriceFlag(), 0)) {
            BigDecimal orderTotalPrice =
                    ibamuPurchaseApplyService.getTotalPriceByContractId(projectOrderSaveDto.getContractId());
            if (orderTotalPrice == null) {
                orderTotalPrice = new BigDecimal(0);
            }
            orderTotalPrice.add(ConvertUtil.getBigDecimalValue(totalPrice, BigDecimal.ZERO));

            if (orderTotalPrice.compareTo(bamuSaleContract.getContractTotalRealPrice()) > 0) {
                errorMsg.append("采购订单金额：").append(orderTotalPrice).append(" 超出合同金额：").append(bamuSaleContract.getContractTotalRealPrice()).append("，请修改后重试；");
            }
        }
        errorMsg.append(errorNumMsg);
        if (errorMsg.length() > 0) {
            return YResult.error(errorMsg.toString());
        } else {
            return YResult.success("");
        }
    }

    /*
     * @Description: 是否完全供货
     */
    @Override
    public YResult<CheckSupplyVO> checkSupplyStatus(ProjectOrderDto orderDto) {
        CheckSupplyVO checkSupplyVO = new CheckSupplyVO();
        BamuPurchaseApply bamuPurchaseApply = ibamuPurchaseApplyService.getById(orderDto.getId());
        /**
         * 项目订单材料
         */
        LambdaQueryWrapper<BamuPurchaseApplyMaterial> materialQueryWrapper =
                new LambdaQueryWrapper<>();
        materialQueryWrapper.eq(BamuPurchaseApplyMaterial::getPurchaseApplyId,
                bamuPurchaseApply.getId()).eq(BamuPurchaseApplyMaterial::getIsDeleted,
                DataDeletedStatus.NO.getType());
        List<BamuPurchaseApplyMaterial> applyMaterialList =
                ibamuPurchaseApplyMaterialService.list(materialQueryWrapper);
        if (CollectionUtils.isEmpty(applyMaterialList)) {
            return YResult.error("该项目订单没有材料");
        }

        /**
         * 验收清单材料
         */
        LambdaQueryWrapper<BamuSoSupplyMaterial> bamuSoSupplyLambdaQueryWrapper =
                new LambdaQueryWrapper<BamuSoSupplyMaterial>();
        bamuSoSupplyLambdaQueryWrapper.eq(BamuSoSupplyMaterial::getPurchaseApplyId,
                bamuPurchaseApply.getId()).eq(BamuSoSupplyMaterial::getIsDeleted,
                DataDeletedStatus.NO.getType());
        List<BamuSoSupplyMaterial> supplyList =
                iBamuSoSupplyMaterialService.list(bamuSoSupplyLambdaQueryWrapper);

        if (CollectionUtils.isEmpty(supplyList)) {
            return YResult.error("该项目订单没有验收清单材料");
        }
        /**
         * 生成map， BamuSoSupplyMaterial materialCode 相同的 材料， 计算  BamuSoSupplyMaterial 中
         * materialNum 总和
         */
        Map<String, BigDecimal> supplyMap =
                supplyList.stream().filter(x -> null != x.getSupplyNum()).collect(Collectors.toMap(BamuSoSupplyMaterial::getMaterialCode, BamuSoSupplyMaterial::getSupplyNum, BigDecimal::add));
        Map<String, BigDecimal> applyMap =
                applyMaterialList.stream().filter(x -> null != x.getOrderCount()).collect(Collectors.toMap(BamuPurchaseApplyMaterial::getMaterialCode, BamuPurchaseApplyMaterial::getOrderCount, BigDecimal::add));
        if (null != applyMap && applyMap.size() > 0) {
            for (Map.Entry<String, BigDecimal> entry : applyMap.entrySet()) {
                if (supplyMap.containsKey(entry.getKey())) {
                    BigDecimal applyNum = entry.getValue();
                    BigDecimal supplyNum = supplyMap.get(entry.getKey());
                    if (applyNum.compareTo(supplyNum) == 0) {
                        checkSupplyVO.setIfSupplied("1");
                    } else {
                        checkSupplyVO.setIfSupplied("0");
                        return YResult.success(checkSupplyVO);
                    }
                } else {
                    checkSupplyVO.setIfSupplied("0");
                    return YResult.success(checkSupplyVO);
                }
            }
        }
        checkSupplyVO.setIfSupplied("1");
        return YResult.success(checkSupplyVO);
    }


    @Override
    public List<ProjectOrderExcelDto> export(ProjectOrderDto projectOrderDto) {
        List<BamuPurchaseApply> contractMaterialList = purchaseMappingMapper.getPurchaseApplyList(projectOrderDto);
        if (CollectionUtils.isNotEmpty(contractMaterialList)) {
            return contractMaterialList.stream().map(this::convertToExcelDto).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 将BamuContractMaterial转化成ContractMaterialExportDto
     */
    private ProjectOrderExcelDto convertToExcelDto(BamuPurchaseApply bamuPurchaseApply) {
        ProjectOrderExcelDto dto = new ProjectOrderExcelDto();
        BeanUtils.copyProperties(bamuPurchaseApply, dto);
        dto.setId(bamuPurchaseApply.getId());
        //价格类型转换
        dto.setPriceType(ContractPriceType.typeOfDesc(Integer.parseInt(bamuPurchaseApply.getPriceType())));
        //对账状态
        dto.setProjectReconciliationStatus(ReconciliationStatus.getDescriptionByType(bamuPurchaseApply.getProjectReconciliationStatus()));
        dto.setSupplierReconciliationStatus(ReconciliationStatus.getDescriptionByType(bamuPurchaseApply.getSupplierReconciliationStatus()));
        //结算状态
        dto.setSettlementStatus(SettlementStatus.getDescriptionByType(bamuPurchaseApply.getSettlementStatus()));
        //开票状态
        dto.setProjectInvoiceStatus(InvoiceStatusStatus.getDescriptionByType(bamuPurchaseApply.getProjectInvoiceStatus()));
        dto.setSupplyInvoiceStatus(InvoiceStatusStatus.getDescriptionByType(bamuPurchaseApply.getSupplyInvoiceStatus()));

        StringBuilder status = new StringBuilder();
        String orderStatus = "";
        if ((bamuPurchaseApply.getSupplyStatus() == null || bamuPurchaseApply.getSupplyStatus() == 0) && ConvertUtil.getIntValue(bamuPurchaseApply.getAuditStatus(), -1) != AuditStatusEnums.AUDIT_SUCCESS.getType()) {
            orderStatus =
                    AuditStatusEnums.getDescriptionByType(ConvertUtil.getIntValue(bamuPurchaseApply.getAuditStatus()));
        } else {
            if (bamuPurchaseApply.getSupplyStatus() == SupplyStatus.SUPPLY_COMPLETION_ACCEPTANCE.getType()) {
                if (ConvertUtil.getIntValue(bamuPurchaseApply.getAuditStatus()) == AuditStatusEnums.AUDIT_REJECT.getType() || ConvertUtil.getIntValue(bamuPurchaseApply.getAuditStatus()) == AuditStatusEnums.AUDIT_REVOCATION.getType())
                    status.append(bamuPurchaseApply.getAuditStatus()).append("8");
                orderStatus = OrderStatus.getDescriptionByType(status.toString());
            } else {
                orderStatus = SupplyStatus.getDescriptionByType(bamuPurchaseApply.getSupplyStatus());
            }
        }
        //审批中改为，待云采确认
        if (orderStatus.equals(OrderStatus.APPROVAL_IN_PROGRESS.getDescription())) {
            orderStatus = STATUS_AUDIT;
        }
        //状态
        dto.setOrderStatus(orderStatus);
        dto.setCopperDate(ConvertUtil.getFormatDate(bamuPurchaseApply.getCopperDate(), false, "yyyy-MM-dd"));
        dto.setReceivingTime(ConvertUtil.getFormatDate(bamuPurchaseApply.getReceivingTime(), false, "yyyy"
                + "-MM-dd"));
        dto.setSupplyConfirmDate(ConvertUtil.getFormatDate(bamuPurchaseApply.getSupplyConfirmDate(), false
                , "yyyy-MM-dd"));
        dto.setTakeAt(ConvertUtil.getFormatDate(bamuPurchaseApply.getTakeAt(), false, "yyyy-MM-dd"));
        dto.setFlowSubmitDate(ConvertUtil.getFormatDate(bamuPurchaseApply.getFlowSubmitDate(), false,
                "yyyy-MM-dd"));
        return dto;
    }


}
